package util;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.OSSObject;
import config.OssConfig;
import constant.OssClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;

import java.io.InputStream;

import static constant.CommonConstant.PDF_CONTENT_CACHE;

@Slf4j
public class PdfUtils {

    /**
     * @param pdfUrl oss中存储的pdf地址
     * @return 解析完之后的文档内容
     * */
    public static String pdfToContent(String pdfUrl){
        //https://pdf-container.oss-cn-beijing.aliyuncs.com/2024/07/28/flink.pdf
        OSS ossClient = OssClient.getOssClient();
        if (ossClient == null){
            throw new RuntimeException("OssClient 初始化失败！");
        }
//        pdfUrl = pdfUrl.replace("https://tamude.oss-cn-beijing.aliyuncs.com/", "");
        String path = pdfUrl.replace("https://pdf-container.oss-cn-beijing.aliyuncs.com/", "");
        try {
            // ossObject包含文件所在的存储空间名称、文件名称、文件元数据以及一个输入流。
            OSSObject ossObject = ossClient.getObject(OssConfig.BUCKET, path);
            InputStream inputStream = ossObject.getObjectContent();
            PDDocument pdf = PDDocument.load(inputStream);
            String pdfContent = new PDFTextStripper().getText(pdf);
            PDF_CONTENT_CACHE.putIfAbsent(pdfUrl, pdfContent);
            // ossObject对象使用完毕后必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
            ossObject.close();
            inputStream.close();
            return pdfContent;

        } catch (OSSException oe) {
            log.error("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            log.error("Error Message:{}",oe.getErrorMessage());
            log.error("Error Code:{}",oe.getErrorCode());
            log.error("Request ID:{}",oe.getRequestId());
            log.error("Host ID:{}",oe.getHostId());
        } catch (Throwable ce) {
            log.error("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            log.error("Error Message:{}", ce.getMessage());
        }

        return null;

    }

}
